package com.project.ssmfo.common;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.project.utils.ClientMD5SignMake;
import com.project.utils.StringUtil;

/**
 * 系统拦截器
 */
public class SigInterceptor extends HandlerInterceptorAdapter{
    private static Logger logger = Logger.getLogger(SigInterceptor.class);

    /**
     * session超时拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throws Exception{
    	logger.error("SigInterceptor request");
    	String error = "";
    	String code = "";
    	boolean flag=true;
        String url = request.getRequestURI().replace(request.getContextPath(), "");
        Map<String,String> treeMap = new TreeMap<String, String>();
        Enumeration<String> params = request.getParameterNames();
        String servletPath=request.getServletPath();
        Map<String, Object> map=new HashMap<String, Object>();
		if(request.getParameter("sig")!=null) {//验签方式
			String sig = "";
			while(params.hasMoreElements()){
				String param = params.nextElement();
				if(param!=null&&param.equals("sig")){
					sig = request.getParameter(param);
				}else{
					treeMap.put(param, request.getParameter(param));
				}
			}
			if(validSig(treeMap,sig)){
        		logger.info("sig="+sig);
        	}else{
        		code=Configuration.WRONG;
        		error="权限不足";
        		flag=false;
        	}
		}else if("000".equals(request.getParameter("decrypt"))) {//解密成功
			try {
//				String agent = request.getHeader("user-agent").toLowerCase();
				if (StringUtils.isNotBlank(request.getParameter("timestamp"))) {
					long validate_seconds = StringUtil.toLong(Configuration.get("validate_seconds"));
					if ((System.currentTimeMillis()
							- StringUtil.toLong(request.getParameter("timestamp"))) > validate_seconds * 1000) {
						code = Configuration.OVERTIME;
						error = "已过时";
						flag = false;
					} else if (StringUtils.isNotBlank(request.getParameter("signaccount")) 
							|| StringUtils.isNotBlank(request.getParameter("uid"))) {
						String uid = request.getParameter("signaccount");
						if(StringUtil.isEmpty(uid)) {
							uid = request.getParameter("uid");
						}
						
						
					}
				} else {
					code = Configuration.MISSING;
					error = "缺少时间戳";
					flag = false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				code = Configuration.WRONG;
				error = "系统出错";
				flag = false;
			}
		}else if(Configuration.RELOGIN.equals(request.getParameter("decrypt"))){
			code = Configuration.RELOGIN;
			error = "数据校验失败，请重新登录";
			flag = false;
		}else {
			code = Configuration.WRONG;
			error = "权限不足";
			flag=false;
		}
		if(!flag) {
			map.put("code", code);
	    	map.put("reason", error);
//	    	response.setHeader("Content-type", "text/html;charset=UTF-8");
	    	response.setHeader("Content-type", "text/json;charset=UTF-8"); 
	    	response.setCharacterEncoding("UTF-8");
			response.getWriter().print(JSONObject.toJSONString(map));
		}
		return flag;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
    		ModelAndView modelAndView) throws Exception {
    	
//    	if(request.getParameter("data_v4")!=null) {
//    		PrintWriter writer = response.getWriter();
//    		String RESPONSE_KEY=Configuration.get("response_key");
//    		EncryptHttpResponseWrapper wrapResponse = new EncryptHttpResponseWrapper(
//                    (HttpServletResponse) response);
//    		byte[] data = wrapResponse.getResponseData(); 
//    		logger.debug("原始返回数据： " + new String(data, "utf-8")); 
//    		// 加密返回报文 
//    		String responseBodyMw = AESUtil.encryptHex(new String(data, "utf-8"), RESPONSE_KEY); 
//    		logger.debug("加密返回数据： " + responseBodyMw); 
//    		writeResponse(response, responseBodyMw);
//        }
    	
    }
    
//    private void writeResponse(ServletResponse response, String responseString) throws IOException { 
//    	PrintWriter out = response.getWriter(); 
//    	out.print(responseString); 
//    	}

    
    
    public static boolean validSig(Map map, String sig) {
		String localsig = ClientMD5SignMake.makeMD5Sign(map, Configuration.getFrontValidKey());
		logger.error("treeMap============="+JSONObject.toJSONString(map));
		logger.error("sig================"+sig);
		logger.error("localsig===================="+localsig);
		if (localsig != null && localsig.equals(sig)) {
			return true;
		} else {
			return false;
		}
	}
    
	/**
	 * <p>Title: combineKey</p>
	 * <p>Description: 按规则组合key</p>
	 * @param csrf_token
	 * @param fixed_key
	 * @param access_key
	 * @return String
	 */
	public static String combineKey(String csrf_token,String fixed_key,String access_key) {
		return getAfterRuleStr(csrf_token)+reverse(fixed_key)+afterServerRuleStr(access_key);
	}
	
	/**
	 * 按混淆规则对客户端秘钥进行重新组合
	 */
	public static String getAfterRuleStr(String val) {
		val=val.trim();
		String regEx="[^0-9]";   
		Pattern p = Pattern.compile(regEx);   
		Matcher m = p.matcher(val);
		String number=m.replaceAll("").trim();
		String numberSort="";
		int max=0;
		int minodd=9;
		int mineven=8;
		int index1=Integer.valueOf(number.substring(0, 1));
		int index6=Integer.valueOf(number.substring(5, 6));
		for (int i = 0; i <number.length(); i++)
        {
            numberSort = number.substring(i, i+1) + numberSort;
            Integer a=Integer.valueOf(number.substring(i, i+1));
            if(max<a) max=a;
            if(a%2>0) {
            	if(minodd>a) minodd=a;
            }else {
            	if(mineven>a) mineven=a;
            }	
            
        }
		int rand=((index1+index6)*max)%mineven+minodd;
		val="";
		for(int i = 0; i <numberSort.length(); i++){
			int b= Integer.valueOf(numberSort.substring(i, i+1))*rand;
			if(b<10) {
				val=b+"0" + val;
			}else {
				val=b%10+""+b/10 + val;
			}
		}
		return val;
	}
	
	/**
	 * <p>Title: reverse</p>
	 * <p>Description: 颠倒字符串顺序</p>
	 * @param val
	 * @return String
	 */
	public static String reverse(String val) {
		String numberSort="";
		for (int i = 0; i <val.length(); i++)
        {
            numberSort = val.substring(i, i+1) + numberSort;
        }
		val=numberSort;
		return val;
		
	}
	
	/**
	 * 按混淆规则对服务器端秘钥进行重新组合
	 */
	public static String afterServerRuleStr(String val) {
		String str1=val.substring(4, 8);
		String str2=val.substring(0, 4);
		 char[] ch = str1.toCharArray();  
	     StringBuffer sbf = new StringBuffer();
	     for(int i=0; i< 4; i++){  
	           sbf.append(charToUpperCase(ch[i]));  
	      }
	     sbf.append(str2);
	     val=sbf.substring(0,2)+ sbf.substring(4,6)+sbf.substring(2,4)+ sbf.substring(6,8);
		return val;
	}
	
	
	/**转大写**/  
    public static char charToUpperCase(char ch){  
        if(ch <= 122 && ch >= 97){  
            ch -= 32;  
        }  
        return ch;  
    }  
    /***转小写**/  
    public char charToLowerCase(char ch){  
        if(ch <= 90 && ch >= 65){  
            ch += 32;  
        }  
        return ch;  
    }
}